<template>
  <div class="defectOrderDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :moreBtnArr="moreBtnArr"
      :showMore="showMore"
      showStep
      showTopTitle
      :creatInfo="formData"
      :closeBox="closeCheckRecord"
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        大修工单 {{ formData.code }}
      </template>
      <div class="orderTitle">
        <div class="tipText">
          标题自动生成规则：{设备管理单位名称}{设备名称}+大修
        </div>
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span class="titleText" :title="orderTitle">{{ orderTitle }}</span>
          <el-link
            v-show="!baseAttachBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!--  :class="{remindColor:!userInput}" -->
          <el-input
            type="text"
            v-model="orderTitle"
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend">标题</template>
          </el-input>
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">基本信息</template>
          <detailForm
            ref="basicForm"
            :initData="formData"
            :pageType="pageType"
            @changeFormData="changeFormData"
            @setWorkListData="setWorkListData"
            @initUserInput="initUserInput"
            @setOrderTitle="setOrderTitle"
          ></detailForm>
        </el-collapse-item>
        <el-collapse-item name="2" v-if="showWorkList">
          <template slot="title">作业表单</template>
          <workList
            v-if="workListData.length > 0"
            ref="workList"
            :formData="workListData"
            :pageType="pageType"
            :disabled="baseAttachBtn"
            :formStandard="formStandard"
            :status="status"
          ></workList>
          <div class="noData" v-else>此设备无作业表单</div>
        </el-collapse-item>
        <el-collapse-item name="3" v-if="showDispatch">
          <template slot="title">派工信息</template>
          <dispatch
            ref="dispatch"
            :formData="formData"
            :pageType="pageType"
            orderType="overhaul"
            @changeData="getDetails"
            @setDispatchTime="setDispatchTime"
          />
        </el-collapse-item>
        <div v-if="showWorkTicket && haveTicketData">
          <el-collapse-item name="4">
            <template slot="title">工作票信息</template>
            <wokTicketList
              :orderId="formData.id"
              @haveData="(val) => (haveTicketData = val)"
            ></wokTicketList>
          </el-collapse-item>
        </div>
        <div v-if="showWorkTicket && haveServiceData">
          <el-collapse-item name="5">
            <template slot="title">检修申请信息</template>
            <serviceList
              :orderId="formData.code"
              @haveData="(val) => (haveServiceData = val)"
            ></serviceList>
          </el-collapse-item>
        </div>

        <el-collapse-item name="6" v-if="showWorkListNext">
          <template slot="title">作业表单</template>
          <workListExecute
            ref="workListExecute"
            :formData="formData"
            :pageType="pageType"
            :disabled="editWorkList"
            @updateData="getDetails"
          ></workListExecute>
        </el-collapse-item>
        <el-collapse-item name="7" v-if="showPerform">
          <template slot="title">执行信息</template>
          <performInfo
            :formData="formData"
            :pageType="pageType"
            :btnJurisdiction="btnJurisdiction"
            ref="performInfo"
            v-if="showPerform"
          ></performInfo>
        </el-collapse-item>
        <el-collapse-item name="8" v-if="showPerform">
          <template slot="title">试验工单信息</template>
          <div class="testOrderBtn" v-if="status == 'IN_EXECUTE'">
            <el-tooltip
              class="item"
              effect="dark"
              :disabled="showTestBtn"
              :content="testTitle"
              placement="top-start"
            >
              <div class="btnDiv">
                <el-button
                  class="el-button--plain"
                  size="mini"
                  icon="el-icon-plus"
                  @click="selectTestOrder"
                  :disabled="!showTestBtn"
                  >关联试验工单</el-button
                >
              </div>
            </el-tooltip>
          </div>
          <div class="testTable">
            <listTableNew v-bind="testSetting" ref="testTable"></listTableNew>
          </div>
          <!-- <editTableNew :tableSetting="testConfig" ref="testTable" /> -->
        </el-collapse-item>
        <el-collapse-item name="9" v-if="showPerform">
          <template slot="title">分级分项验收信息</template>
          <baseTable
            :tableSetting="classConfig"
            ref="classTable"
            class="classficationTable"
          />
        </el-collapse-item>
        <el-collapse-item name="10" v-if="showReportm">
          <template slot="title">大修报告</template>
          <report
            ref="report"
            :formData="formData"
            :pageType="pageType"
            @perform="perform"
          ></report>
        </el-collapse-item>
        <el-collapse-item name="11" v-if="showWorkFlow">
          <template slot="title">验收审批信息</template>
          <div v-if="formData.sourceId == 'import_order_eam1.0'">
            数据来源EAM1.0,流程信息无法展示
          </div>
          <workFlow
            v-else
            ref="workFlow"
            :isDetails="pageType == 'query'"
            :currentFlowData="formData"
            @submitSuccess="workFlowSuccess"
            workflowCode="overhaul_accept"
          ></workFlow>
        </el-collapse-item>
      </el-collapse>
      <template slot="boxContent">
        <checkRecord
          v-if="showCheckRecord"
          :orderData="formData"
          ref="checkRecord"
        ></checkRecord>
      </template>
    </editPageNew>
    <dialogPublic
      :title="'审核信息'"
      :show.sync="showFlowDialog"
      noFootBtn
      appendTobody
      fullscreen
      @doClose="() => (showFlowDialog = false)"
    >
      <workFlow
        v-if="showFlowDialog"
        :isDetails="pageType == 'query'"
        :currentFlowData="formData"
        @submitSuccess="workFlowSuccess"
        workflowCode="overhaul_accept"
      ></workFlow>
    </dialogPublic>
    <dialogPublic
      title="关联试验工单"
      :show.sync="showTestOrder"
      v-if="showTestOrder"
      :fullscreen="true"
      @doSubmit="correlationTest"
      @doClose="() => (showTestOrder = false)"
    >
      <orderList
        :searchData="searchData"
        selectType="overhaul"
        ref="orderList"
        v-if="showTestOrder"
      ></orderList>
    </dialogPublic>
    <dialogPublic
      :title="'转派工单'"
      :show.sync="showRedeploy"
      @doClose="() => (showRedeploy = false)"
      @doSubmit="toRedeploy"
      appendTobody
    >
      <div class="h100">
        <editForm
          v-if="showRedeploy"
          :formConfig="redeployConfig"
          ref="redeployForm"
          :formData="redeployData"
        />
      </div>
    </dialogPublic>
  </div>
</template>
<script>
import {
  saveOrUpdate, //保存大修工单
  deleteApi, //删除工单
  submitOrder, //大修执行中提交状态修改
  addExperimentApi, //新增大修工单与试验工单的关联表
  getExperimentApi, //根据id查询大修工单与试验工单的关联表
  deleteExperimentApi, //删除大修工单与试验工单的关联表
  invalidApi, //作废
} from "@/api/orderManagement/overhaul";
import {
  getOrderDictionApi, //权限
  queryTicketByOrderId, //根据工单id查询关联的工作票
} from "@/api/orderManagement/common";
import workList from "./workList";
import orderList from "./orderList.vue";
import report from "./report";
import checkRecord from "../checkRecord";
import workListExecute from "./workListExecute";
import baseTable from "@/components/table/baseTable";
import performInfo from "./performInfo";
import dispatch from "@/views/orderManagement/publicModule/dispatch";
import detailForm from "./detailForm";
import wokTicketList from "../wokTicketList";
import serviceList from "../serviceList";
import { redeployApi } from "@/api/orderManagement/defectOrder";
import { sendMessageToQywx } from "@/api/common.js"
export default {
  components: {
    workList,
    dispatch,
    workListExecute, //执行中作业表单
    performInfo, //
    report, //大修报告
    baseTable,
    checkRecord, //工单抽查
    detailForm,
    orderList,
    wokTicketList, //关联的工作票列表
    serviceList,
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      userInput: false,
      showInput: false,
      showTestOrder: false,
      haveTicketData: true,
      haveServiceData: true,
      showMore: false,
      searchData: {
        orderType: "experiment",
        overhaulRel: -1,
      },
      orderId: "",
      showCheckRecord: false,
      currentEquipmentName: "", //设备
      equipmentDeptName: "", //设备
      currentContext: "", //工作内容
      workListData: [], //作业表单数据
      unfinished: [], //未完成的部分
      btnJurisdiction: [], //权限
      currentDevice: {},
      orderTitle: "",
      status: "",
      formStandard: false, //作业表单的数据是否来自大修标准
      activeNames: ["1", "2"], //
      editFormData: { status: "" },
      creatInfo: {},
      showFlowDialog: false,
      acceptanceUnfold: false,
      hideBtnNo: true,
      parameterList: [],
      filesList: [],
      /* 工作班成员 */
      workerList: [],
      chooseData: [],
      tempTableData: [], //临时设备参数表格数据
      moveData: {},
      deptOption: [],
      userOption: [],
      formData: {},
      dispatchData: {},
      acceptData: {},
      pageType: "",
      orderStatus: [
        "DRAFT",
        "WAIT_DISPATCH",
        "WAIT_EXECUTE",
        "IN_EXECUTE",
        "PREPARE_REPORT",
        "WAIT_ACCEPT",
        "ARCHIVED",
      ],
      testSetting: {
        showPagination: false,
        showCustomBtn: false,
        showFilterBtn: false,
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {},
          searchArr: [],
        },
        actionList: [],
        column: [
          {
            label: "编号",
            prop: "code",
          },
          {
            label: "标题",
            prop: "title",
          },
          {
            label: "设备管理单位",
            prop: "deptManageName",
          },
          {
            label: "工作单位",
            prop: "workDept",
            scopeType: "formate",
            method: (row) => {
              let name = [];
              let list = row.workDeptPoList || [];
              if (list.length > 0) {
                list.map((i) => {
                  name.push(i.workDeptName);
                });
              }
              return name.toString();
            },
          },
          {
            label: "计划开始时间",
            prop: "startTime",
          },
          {
            label: "计划结束时间",
            prop: "endTime",
          },
          {
            label: "状态",
            prop: "status",
            width: 100,
            formatter: (row) => {
              return this.$store.getters["fineDirtDataName"](
                "order_experiment_type",
                row.status
              );
            },
          },
          {
            label: "创建时间",
            prop: "createTime",
            textAlign: "center",
          },
          {
            label: "试验报告",
            prop: "attachmentList",
            title: "点击下载试验报告",
            btnProp: "name",
            textAlign: "center",
            type: "textButtonList",
            method: (obj, index) => {
              let fileName = obj.name;
              this.$utils.downloadFile(obj.id, fileName);
            },
          },
          {
            label: "操作",
            textAlign: "center",
            type: "button",
            width: "80px",
            hide: this.status != "IN_EXECUTE",
            buttonArr: [
              {
                text: "删除",
                isShow: () => {
                  return true;
                },
                methods: (row) => {
                  this.deleteTestRow(row);
                },
              },
            ],
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {
            this.goToDetails("experimentOrderDetails", { id: val.id });
          },
        },
      },
      classConfig: {
        height: "400px",
        indexShow: true,
        noBorderRight: false,
        column: [
          {
            label: "编号",
            prop: "code",
            textAlign: "center",
          },
          {
            label: "分级分项名称",
            prop: "name",
            textAlign: "center",
          },
          {
            label: "专业",
            prop: "major",
            // width: 100,
            textAlign: "center",
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val.major
              );
            },
          },
          {
            label: "验收级别",
            prop: "level",
            textAlign: "center",
          },
          {
            label: "现场负责人",
            prop: "joberName",
            textAlign: "center",
          },
          {
            label: "状态",
            prop: "status",
            textAlign: "center",
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "overhaul_status",
                val.status
              );
            },
          },
        ],
        rowClick: (data) => {
          this.gotoClassificationDetails(data);
        },

        data: [],
      },
      redeployConfig: {
        itemArr: [
          {
            type: "select",
            label: "缺陷专业",
            prop: "major",
            required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            span: 24,
          },
          {
            label: "责任人",
            prop: "workerName", //多选时，字段要为数组类型
            propArr: "workerArr",
            idsStr: "worker",
            orgStr: "workerType", //是否是外单位，人员类型
            orgNameStr: "workerDeptName",
            orgIdStr: "workerDept",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: (obj) => {},
            required: true,
            span: 24,
          },
          {
            label: "转派原因",
            prop: "reason",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 6,
          },
        ],
      },
      redeployData: {},
      showRedeploy: false,
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          hide: [
            "WAIT_EXECUTE",
            "IN_EXECUTE",
            "WAIT_ACCEPT",
            "ARCHIVED",
            "DEPRECATED",
          ].includes(this.status),
          methods: () => {
            this.doSubmit("save");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "save",
            this.$store.getters["isBtnAuth"]("save")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("save") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "save")
          ),
        },
        {
          text: "提交",
          icon: "el-icon-position",
          hide: [
            "WAIT_DISPATCH",
            "WAIT_EXECUTE",
            "WAIT_ACCEPT",
            "ARCHIVED",
            "DEPRECATED",
          ].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "submit",
            this.$store.getters["isBtnAuth"]("submit")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("submit") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "submit")
          ),
          methods: () => {
            if (this.status == "IN_EXECUTE") {
              this.perform();
            } else {
              this.doSubmit("submit");
            }
          },
        },
        {
          text: "派工",
          icon: "el-icon-position",
          hide: this.status != "WAIT_DISPATCH",
          methods: () => {
            this.doSubmit("submit");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "dispatch",
            this.$store.getters["isBtnAuth"]("dispatch")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("dispatch") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "dispatch")
          ),
        },
        {
          text: "执行",
          icon: "el-icon-position",
          hide: this.status != "WAIT_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "execute",
            this.$store.getters["isBtnAuth"]("execute")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("execute") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "execute")
          ),
          methods: () => {
            this.perform();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          hide:
            this.status != "DRAFT" || this.formData.sourceId == "plan_order",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "delete",
            this.$store.getters["isBtnAuth"]("delete")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("delete") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "delete")
          ),
          methods: () => {
            this.deleteData();
          },
        },
      ];
      return arr;
    },
    showTestBtn() {
      //派工信息
      return (
        this.$store.getters["isBtnAuth"]("linkExperiment") &&
        this.$utils.getJurisdiction(this.btnJurisdiction, "linkExperiment")
      );
    },
    testTitle() {
      //派工信息
      return this.$utils.getJurisdictionContent(
        this.btnJurisdiction,
        "linkExperiment",
        this.$store.getters["isBtnAuth"]("linkExperiment")
      );
    },
    stepConfig() {
      let obj = {};
      let step = 0;
      if (this.status == "DEPRECATED") {
        obj = {
          nowStep: 0, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["已废弃"],
        };
      } else {
        step = this.orderStatus.indexOf(this.status);
        obj = {
          nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: [
            "草稿",
            "待派工",
            "待执行",
            "执行中",
            "编制大修报告",
            "待验收",
            "已归档",
          ],
        };
      }
      return obj;
    },
    editWorkList() {
      let status = this.status;
      return ["WAIT_EXECUTE"].includes(status);
    },
    moreBtnArr() {
      let arr = [
        {
          text: "办理工作票",
          methods: (item) => {
            this.selectTicketType(item);
          },
          hide: !["WAIT_EXECUTE", "IN_EXECUTE"].includes(this.status),
          isDictionary: true, //是否是数据字典
          child: this.$store.getters["dirtData"]("ticket_work_type"),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "handleTicketWork",
            this.$store.getters["isBtnAuth"]("handleTicketWork")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("handleTicketWork") &&
            this.$utils.getJurisdiction(
              this.btnJurisdiction,
              "handleTicketWork"
            )
          ),
        },
        {
          text: "检修申请",
          methods: (val) => {
            if (!val) {
              this.toService();
            }
          },
          hide: !["WAIT_EXECUTE", "IN_EXECUTE"].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "application",
            this.$store.getters["isBtnAuth"]("application")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("application") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "application")
          ),
        },
        {
          text: "转派工单",
          methods: (val) => {
            if (!val) {
              this.showRedeploy = true;
            }
          },
          hide: !["WAIT_DISPATCH", "WAIT_EXECUTE", "IN_EXECUTE"].includes(
            this.status
          ),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "changeDispatch",
            this.$store.getters["isBtnAuth"]("changeDispatch")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("changeDispatch") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "changeDispatch")
          ),
        },
        {
          text: "工单变更",
          methods: (val) => {
            if (!val) {
              this.toChange();
            }
          },
          hide: this.status != "WAIT_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "orderChange",
            this.$store.getters["isBtnAuth"]("orderChange")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("orderChange") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "orderChange")
          ),
        },
        {
          text: "工单抽查",
          hide: this.status != "ARCHIVED",
          methods: () => {
            this.$refs.editPage.showEditPageBox();
            this.showCheckRecord = true;
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "spotCheck",
            this.$store.getters["isBtnAuth"]("spotCheck")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("spotCheck") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "spotCheck")
          ),
        },
        {
          text: "让步接收",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                pageType: "orderAdd",
              };
              this.goToDetails("concessionAcceptDetails", routerForm);
            }
          },
          hide: this.status != "IN_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "concession",
            this.$store.getters["isBtnAuth"]("concession")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("concession") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "concession")
          ),
        },
        {
          text: "重大问题上报",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                pageType: "orderAdd",
              };
              this.goToDetails("majorIssuesDetails", routerForm);
            }
          },
          hide: this.status != "IN_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "question",
            this.$store.getters["isBtnAuth"]("question")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("question") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "question")
          ),
        },
        {
          text: "作废",
          methods: (val) => {
            if (!val) {
              this.toInvalid();
            }
          },
          hide: !["WAIT_DISPATCH", "WAIT_EXECUTE"].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "invalid",
            this.$store.getters["isBtnAuth"]("invalid")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("invalid") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "invalid")
          ),
        },
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
          hide: this.status == "",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "operateRecord",
            this.$store.getters["isBtnAuth"]("operateRecord")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("operateRecord") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "operateRecord")
          ),
        },
        {
          text: "打印",
          methods: () => {
            this.toPrint();
          },
          hide: this.status == "",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "print",
            this.$store.getters["isBtnAuth"]("print")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("print") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "print")
          ),
        },
      ];
      return arr;
    },
    baseAttachBtn() {
      if (
        ["DRAFT", ""].includes(this.status) &&
        ["edit", "add"].includes(this.pageType)
      ) {
        return false;
      } else {
        return true;
      }
    },
    showWorkList() {
      let status = this.status;
      if (["", "DRAFT", "WAIT_DISPATCH", "WAIT_EXECUTE"].includes(status)) {
        return true;
      } else {
        return false;
      }
    },
    showWorkListNext() {
      let status = this.status;
      if (
        ["IN_EXECUTE", "PREPARE_REPORT", "WAIT_ACCEPT", "ARCHIVED"].includes(
          status
        )
      ) {
        return true;
      } else {
        return false;
      }
    },
    showDispatch() {
      let status = this.status;
      //派工信息
      return [
        "WAIT_DISPATCH",
        "WAIT_EXECUTE",
        "IN_EXECUTE",
        "PREPARE_REPORT",
        "WAIT_ACCEPT",
        "ARCHIVED",
      ].includes(this.status);
    },
    showPerform() {
      //执行信息
      return [
        "IN_EXECUTE",
        "PREPARE_REPORT",
        "WAIT_ACCEPT",
        "ARCHIVED",
      ].includes(this.status);
    },
    showWorkTicket() {
      //执行信息
      return [
        "WAIT_EXECUTE",
        "IN_EXECUTE",
        "PREPARE_REPORT",
        "WAIT_ACCEPT",
        "ARCHIVED",
      ].includes(this.status);
    },
    showWorkFlow() {
      //审批信息
      return ["WAIT_ACCEPT", "ARCHIVED"].includes(this.status);
    },
    showReportm() {
      //执行信息
      return ["PREPARE_REPORT", "WAIT_ACCEPT", "ARCHIVED"].includes(
        this.status
      );
    },
  },
  watch: {
    activeNames: {
      handler(val) {
        let item = val[val.length - 1];
        if (item == "8") {
          this.acceptanceUnfold = !this.acceptanceUnfold;
        }
      },
      deep: true,
    },
    status: {
      handler(val) {
        this.formData.status = val;
        this.unfoldMethod();
        //获取权限
        this.jurisdiction();
        this.editFormData.status = val;
        if (val == "") {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
      },
    },
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let { id, pageType } = this.$route.query;
      this.pageType = pageType;
      if (id) {
        this.formData.id = id;
        //判断页面类型
        let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
        this.pageType = haveJurisdiction ? "edit" : "detail";
        this.showInput = false;
        this.getDetails();
      } else {
        //新增
        this.showInput = true;
        this.activeNames = ["1", "2"];
      }
    },
    //折叠与展开
    unfoldMethod() {
      let status = this.status;
      if (["DRAFT", "DEPRECATED"].includes(status)) {
        //草稿
        this.activeNames = ["1", "2"];
      } else if (["WAIT_EXECUTE", "WAIT_DISPATCH"].includes(status)) {
        //待派工、待执行
        this.activeNames = ["3", "4"];
      } else if (["IN_EXECUTE"].includes(status)) {
        //执行中
        this.activeNames = ["4", "5", "6", "7", "8", "9"];
      } else if (status == "PREPARE_REPORT") {
        //编制大修报告
        this.activeNames = ["10"];
      } else if (status == "WAIT_ACCEPT") {
        //待验收，验收
        this.activeNames = ["11"];
      } else if (status == "ARCHIVED") {
        //待验收，验收
        this.activeNames = [];
      }
    },
    //获取页面权限
    jurisdiction() {
      let form = {
        orderId: this.formData.id,
        orderStatus: this.status,
        orderType: "overhaul",
      };
      getOrderDictionApi(form).then((res) => {
        let data = res.data || [];
        if (Array.isArray(data)) {
          this.btnJurisdiction = data;
        } else {
          this.btnJurisdiction = [];
        }
        this.changePageType();
      });
    },
    /* 结合角色权限，对页面是否可编辑进行控制 */
    changePageType() {
      let status = this.status || "";
      //用户角色权限
      let userJurisdiction = this.$store.getters["isBtnAuth"]("edit");
      //业务控制权限
      let businessJurisdiction = this.$utils.getJurisdiction(
        this.btnJurisdiction,
        "save"
      );
      let haveJurisdiction = userJurisdiction && businessJurisdiction;
      //确定pageType类型
      this.pageType = haveJurisdiction ? "edit" : "detail";
    },
    getDetails(id) {
      if (this.$refs.basicForm) {
        this.$refs.basicForm.getDetails(id);
      }
    },
    //转派工单
    async toRedeploy() {
      this.showRedeploy = false;
      let data = await this.$refs.redeployForm.getFormData();
      if (this.status == "WAIT_DISPATCH") {
        data.dispatch = false;
      } else {
        data.dispatch = true;
      }
      data.preMajor = this.formData.major;
      data.orderId = this.formData.id;
      data.orderType = "overhaul";
      data.workerType = this.$utils.changeUserType(data.workerType);
      redeployApi(data).then((res) => {
        this.$message.success("操作成功");
        this.$utils.addOperateLog(
          this.formData.id,
          `转派给:${data.workerDeptName} ${data.workerName}`
        );
        this.$refs.basicForm.getDetails(this.formData.id);
        if (this.status == "WAIT_DISPATCH") {
          setTimeout(() => {
            this.jurisdiction();
          }, 200);
        }
      });
    },
    async doSubmit(type) {
      let status = this.formData.status;
      let canSubmit = true;
      let data = {};
      //基本信息的保存
      if (status == "DRAFT" || (this.pageType == "add" && status == null)) {
        //新增或者草稿状态时，保存大修工单-基本信息，提交大修工单-基本信息
        if (type == "submit") {
          data = await this.$refs.basicForm.getFormData();
        } else {
          //保存时不做校验
          data = await this.$refs.basicForm.getFormData(false);
        }
        //判断当前工单标题是否时用户输入的
        data.title = this.orderTitle;
        if (data.dispatchTime) {
          data.startTime = data.dispatchTime[0];
          data.endTime = data.dispatchTime[1];
        }
        data.orderLocationList = this.$refs.basicForm.getLocationList(); //作业地点
        delete data.dispatchTime;
        delete data.location;
        delete data.locationArr;
        delete data.locationName;
        if (this.workListData.length > 0) {
          //有作业表单
          data.majors = await this.$refs.workList.getAllWorkListData(); //作业表单的数据
        }
        if (type == "submit") {
        }
        if (this.workListData.length == 0 && type == "submit") {
          this.$message.warning(
            "当前设备没有大修标准作业表单，无法生成大修工单！"
          );
        } else {
          this.workListData = data.majors;
          if (type == "save") {
            data.status = "DRAFT";
          } else if (type == "submit") {
            data.status = "WAIT_DISPATCH";
          }
          this.saveData(data, type);
        }
      } else if (status == "WAIT_DISPATCH") {
        //待派工状态时，保存大修工单-派工信息，提交大修工单-派工信息
        this.$refs.dispatch.saveData(type);
        this.getDetails();
      } else if (status == "PREPARE_REPORT") {
        //编制大修报告
        this.$refs.report.saveReport(type);
        //this.getDetails();
      }
    },
    saveData(data, type) {
      saveOrUpdate(data).then(async (res) => {
        this.$utils.updateStorage();
        this.$message.success("操作成功！");
        await this.$refs.basicForm.setAttachId(res.data, this.pageType);
        if (this.pageType == "add") {
          this.pageType = "edit";
          this.formData.id = res.data;
          if (type == "submit") {
            this.$utils.addOperateLog(this.formData.id, "新增并提交-大修工单");
          } else {
            this.$utils.addOperateLog(this.formData.id, "新增-大修工单");
          }
          this.changeRouter(type);
        } else if (this.status == "DRAFT" && type == "submit") {
          this.$utils.addOperateLog(this.formData.id, "修改并提交-大修工单");
          this.getDetails(res.data);
        } else {
          this.$utils.addOperateLog(this.formData.id, "修改-大修工单");
          this.getDetails(res.data);
        }
      });
    },

    changeRouter(type) {
      /* 修改路由参数 */
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      obj = Object.assign(obj, {
        id: this.formData.id,
        pageType: "edit",
        status: type == "submit" ? "WAIT_DISPATCH" : "DRAFT",
      });
      this.$router.push({
        query: obj,
      });
    },
    //执行
    async perform() {
      let status = this.formData.status;
      let account = this.userInfo.id;
      //验证是否可以提交
      let index = this.orderStatus.indexOf(this.status);
      let form = {
        id: this.formData.id,
        status: this.orderStatus[index + 1],
        submitTime: this.$utils.TimeFormat(Date.now())
      };
      let canSubmit = true;
      /* 验证是否填写了执行信息 */

      /* 执行中提交(有作业表单时)-判断作业表单是否填写完整 */
      if (status == "IN_EXECUTE" && canSubmit) {
        /* 执行中提交(有作业表单时)-判断作业表单是否填写完整 */
        canSubmit = await this.judgeComplete();
        if (canSubmit) {
          /*执行中 判断分级分项验收单是否已经走完了 */
          let classData = this.formData.grades || [];
          for (let i = 0; i < classData.length; i++) {
            if (classData[i].status != "ARCHIVED") {
              canSubmit = false;
              this.$message.warning("分级分项验收单未全部完成，不能提交！");
              break;
            }
          }
          if (canSubmit) {
            /* 执行中，判断试验工单是否全部到达已归档的状态，若没有，则不能提交 */
            let testList = this.formData.experimentVoList || [];
            for (let i = 0; i < testList.length; i++) {
              if (testList[i].status != "ARCHIVED") {
                canSubmit = false;
                this.$message.warning("试验工单未全部完成已归档，不能提交！");
                break;
              }
            }
          }
        } //验证执行信息是否填写完成
        if (canSubmit) {
          canSubmit = this.$refs.performInfo.judgeIsComplete();
        }
      }
      if (canSubmit) {
        if (status == "PREPARE_REPORT") {
          this.showFlowDialog = true;
        } else {
          /* 在工单的“待执行”页面点执行按钮时：
          如果关联的工作票中存在填写/待签发/待会签/待接收/待许可状态的，弹出询问框“当前存在未许可的工作票，是否继续？”。
          在工单的“执行中”页面提交到下一状态时：
          如果关联的工作票中存在未归档的，弹出询问框“当前存在未归档的工作票，是否继续？” */
          if (["WAIT_EXECUTE", "IN_EXECUTE"].includes(status)) {
            let message = "";
            let res = await queryTicketByOrderId(this.formData.id);
            let workStatus = res.data || [];
            if (workStatus.length > 0) {
              //有关联工作票
              let arr = [];
              if (status == "WAIT_EXECUTE") {
                arr = [1, 2, 3, 4, 5];
              } else {
                arr = [1, 2, 3, 4, 5, 6, 7];
              }
              //取交集
              let intersection = workStatus.filter((val) => {
                return arr.indexOf(val) > -1;
              });
              if (intersection.length > 0) {
                //有交集
                if (status == "IN_EXECUTE") {
                  message = "未归档";
                } else {
                  message = "未许可";
                }
              }
              if (message) {
                this.$confirm(`当前存在${message}的工作票，是否继续?`, "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.performOrder(form, status);
                  })
                  .catch((e) => {});
              } else {
                this.performOrder(form, status);
              }
            } else {
              //没有关联工作票
              this.performOrder(form, status);
            }
          } else {
            this.performOrder(form, status);
          }
        }
      }
    },
    performOrder(form, status) {
      this.$refs.dispatch.getDispatchData().then(resp => {
        let sendMessageParam = {}
        if(status === 'WAIT_EXECUTE') {
          sendMessageParam = {
            title: this.formData.title,
            handler: resp.worker || resp.trackPersonId
          }
        }
        if(status === 'IN_EXECUTE') {
          sendMessageParam = {
            title: this.formData.title,
            handler: this.formData.createBy
          }
        }
        // 发送消息
        sendMessageToQywx(sendMessageParam).then(() => {
          submitOrder(form).then((res) => {
            this.$utils.updateStorage();
            if (status == "IN_EXECUTE") {
              this.$utils.addOperateLog(this.formData.id, "提交-执行信息");
            } else if (status == "WAIT_EXECUTE") {
              this.$utils.addOperateLog(this.formData.id, "执行-大修工单");
            }
            this.$message.success("操作成功");
            this.getDetails();
          });
        })
      })
    },

    //判断大修作业表单是否已填写完整
    async judgeComplete() {
      //判断表单是否填写完整
      let majorsData = this.formData.majors;
      let isCommit = true;
      let majorName = "";
      let formName = "";
      let message = "";
      for (let index = 0; index < majorsData.length; index++) {
        let formData = majorsData[index].forms || [];
        if (isCommit) {
          for (let formIndex = 0; formIndex < formData.length; formIndex++) {
            //表单的数据
            try {
              let data = await this.$refs.workListExecute.getFormData(
                index,
                formIndex
              );
            } catch (e) {
              majorName = majorsData[index].majorName;
              formName = formData[formIndex].name;
              message = "作业表单未填写完整";
              isCommit = false;
              break;
            }
            //表格数据
            if (isCommit) {
              let executeData = await this.$refs.workListExecute.getTableData(
                index,
                formIndex
              );
              let data = executeData;
              for (let i = 0; i < data.length; i++) {
                let child = data[i].children || [];
                if (child.length > 0) {
                  //有子层级
                  for (let j = 0; j < child.length; j++) {
                    let params = child[j].itemParams;
                    let signs = child[j].signs;
                    if (child[j].result == null) {
                      majorName = majorsData[index].majorName;
                      formName = formData[formIndex].name;
                      message = "作业过程状态未确认";
                      isCommit = false;
                      break;
                    } else if (params.length > 0) {
                      //有数据记录项
                      for (let k = 0; k < params.length; k++) {
                        if (["", null].includes(params[k].value)) {
                          majorName = majorsData[index].majorName;
                          formName = formData[formIndex].name;
                          message = "数据记录项未填写完整";
                          isCommit = false;
                          break;
                        }
                      }
                    }
                    //判断是否签名
                    if (isCommit) {
                      if (!signs || signs.length == 0) {
                        majorName = majorsData[index].majorName;
                        formName = formData[formIndex].name;
                        message = "作业过程未签名";
                        isCommit = false;
                      }
                    }
                    if (isCommit == false) {
                      break;
                    }
                  }
                } else {
                  //只有一层
                  let params = data[i].itemParams; //数据记录项
                  let signs = data[i].signs; //签名人
                  //确认状态
                  if (data[i].result == null) {
                    isCommit = false;
                    majorName = majorsData[index].majorName;
                    formName = formData[formIndex].name;
                    message = "作业过程状态未确认";
                    break;
                  } else if (params.length > 0) {
                    //有数据记录项
                    for (let k = 0; k < params.length; k++) {
                      if (["", null].includes(params[k].value)) {
                        majorName = majorsData[index].majorName;
                        formName = formData[formIndex].name;
                        message = "数据记录项未填写完整";
                        isCommit = false;
                        break;
                      }
                    }
                  }
                  //判断是否签名
                  if (isCommit) {
                    if (signs.length == 0) {
                      majorName = majorsData[index].majorName;
                      formName = formData[formIndex].name;
                      message = "作业过程未签名";
                      isCommit = false;
                    }
                  }
                  if (isCommit == false) {
                    majorName = majorsData[index].majorName;
                    formName = formData[formIndex].name;
                    break;
                  }
                }
              }
            }
          }
        } else {
          break;
        }
      }
      if (isCommit == false) {
        this.$message.warning(
          "作业表单：" + majorName + "-" + formName + message
        );
        return false;
      } else {
        return true;
      }
    },
    //删除
    deleteData() {
      let sourceId = this.formData.sourceId;
      //对数据来源进行判断enter_order
      if (this.status == "DRAFT" && sourceId == "enter_order") {
        this.$confirm(`是否确认删除`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            deleteApi(this.formData.id).then((res) => {
              this.$message.success("操作成功");
              this.$utils.updateStorage();
              this.$refs.editPage.closePage();
            });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("只能删除手工录入的数据！");
      }
    },
    //根据是否是外单位改变界面显示
    changeConfig(obj) {
      let itemArr = this.dispatchConfig.itemArr;
      for (let i in itemArr) {
        if (itemArr[i].prop == "trackPerson") {
          if (obj.value == 1) {
            //外单位
            itemArr[i].isHide = false;
          } else {
            itemArr[i].isHide = true;
          }
        }
        //设置选人以及选单位的组件是本单位还是外单位
        if (
          itemArr[i].prop == "headName" ||
          itemArr[i].prop == "deptWorkName"
        ) {
          //负责人
          itemArr[i].isOutOrg = obj.value;
        }
      }
    },
    //工作流提交成功之后
    async workFlowSuccess() {
      if(this.formData.status == 'PREPARE_REPORT') {
        // TODO
        let sendMessageParam = {}
        sendMessageParam = {
          title: this.formData.title,
          handler: this.formData.createBy
        }
        await sendMessageToQywx(sendMessageParam)
      }
      this.$utils.updateStorage();
      this.showFlowDialog = false;
      if (this.$refs.workFlow) {
        this.$refs.workFlow.getFlowInfo();
      }
      //this.$utils.addOperateLog(this.formData.id, "审批-缺陷工单");
      this.$utils.updateStorage();
      this.$refs.basicForm.getDetails();
    },

    setDispatchTime(obj) {
      this.formData = Object.assign(this.formData, obj);
    },

    //用户输入工单标题
    userInputTitle(val) {
      if (val) {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    },
    //打开详情页
    gotoClassificationDetails(data) {
      // if (data) {
      //   this.pageType = "edit";
      // }
      let form = {
        pageType: this.pageType,
      };
      if (this.pageType != "add") {
        form.id = data.id;
        form.status = data.status;
      }
      let { href } = this.$router.resolve({
        path: "/orderManagement/classification/details",
        query: form,
      });
      // window.open(href, "_blank");
      window.open(href);
    },
    //打印预览
    toPrint() {
      window.print();
    },
    //选择工作票类型
    selectTicketType(item) {
      let { id, code } = this.formData;
      let data = { orderId: id, orderCode: code };
      let routerForm = {
        val: JSON.stringify(data) || "",
        pageType: "orderAdd",
        ticketType: item.value,
      };
      this.goToDetails("workTicketProcessingDetails", routerForm);
    },
    goToDetails(name, queryData) {
      const { href } = this.$router.resolve({
        name: name,
        query: queryData,
      });
      window.open(href, "_blank");
    },
    //申请检修
    toService() {
      let { id, code } = this.formData;
      let query = {
        pageType: "orderAdd",
        orderId: id,
        orderCode: code,
      };
      this.goToDetails("overhaulApplicationDetails", query);
    },
    //更新基本信息
    changeFormData(val) {
      this.status = val.status || "";
      this.formData = val;
      setTimeout(() => {
        this.setClassTable();
      }, 200);
    },
    //更新作业表单信息
    setWorkListData(val) {
      this.workListData = val;
    },
    //初始化用户是否自输入了标题
    initUserInput(val) {
      this.userInput = val;
    },
    //用户没有自己输入标题的情况下，根据标题规则自动更新标题
    setOrderTitle(data) {
      if (!this.userInput) {
        this.orderTitle = data;
      }
    },
    //失去焦点
    loseFocus() {
      if (
        ["", null].includes(this.orderTitle) ||
        this.orderTitle.match(/^[ ]*$/)
      ) {
        if (this.$refs.basicForm.getTitle()) {
          this.$message.warning("标题不能为空，已为您自动生成标题！");
          this.orderTitle = this.$refs.basicForm.getTitle();
          this.showInput = false;
        } else {
          this.showInput = true;
        }
      } else {
        this.showInput = false;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //设置试验工单表格数据
    setClassTable(data) {
      if (this.$refs.classTable) {
        this.$refs.classTable.setTableData(this.formData.grades || []);
        let list = this.formData.experimentVoList || [];
        this.$set(this.testSetting, "tableData", list);
      }
    },
    //申请变更
    toChange() {
      let { id, code } = this.formData;
      let form = {
        pageType: "orderAddChange",
        orderId: id,
        orderCode: code,
        orderType: "overhaul",
      };
      let { href } = this.$router.resolve({
        name: "orderChangeDetails",
        query: form,
      });
      window.open(href, "_blank");
    },

    //工单抽查
    closeCheckRecord() {
      this.showCheckRecord = false;
    },
    //关联试验工单
    selectTestOrder() {
      this.searchData.deptManageName = this.formData.deptManageName;
      this.searchData.deptManage = this.formData.deptManage;
      this.showTestOrder = true;
    },
    /* 给大修工单关联试验工单 */
    correlationTest() {
      let data = this.$refs.orderList.getselectData();
      this.showTestOrder = false;
      let ids = [];
      let formObj = [];
      data.map((i) => {
        if (i.id) {
          let obj = {
            experimentId: i.id,
            overhaulId: this.formData.id,
          };
          formObj.push(obj);
        }
      });
      if (data.length > 0) {
        addExperimentApi(formObj).then((res) => {
          this.$message.success("操作成功");
          this.getExperimentList();
        });
      }
    },
    //获取试验工单的数据
    getExperimentList() {
      let form = {
        overhaulId: this.formData.id,
      };
      getExperimentApi(form).then((res) => {
        let list = res.data.list;
        this.$set(this.testSetting, "tableData", list || []);
      });
    },
    //作废
    toInvalid() {
      invalidApi(this.formData.id).then((res) => {
        this.$utils.addOperateLog(this.formData.id, `作废了此工单`);
        this.$utils.updateStorage();
        this.$message.success("操作成功！");
        this.getDetails();
      });
    },
    //删除测试工单
    deleteTestRow(row) {
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let form = {
            experimentId: row.id,
            overhaulId: this.formData.id,
          };
          deleteExperimentApi(form).then((res) => {
            this.$message.success("操作成功");
            this.getExperimentList();
          });
        })
        .catch((e) => {});
    },
  },
};
</script>
<style lang="less" scoped>
.defectOrderDetails {
  background-color: #ffffff;
  .testOrderBtn {
    display: flex;
    flex-flow: wrap nowrap;
  }
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .titleText {
    display: inline-block;
    height: 30px;
    max-width: 800px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 5px;
  }
  .el-link {
    margin-bottom: 5px;
  }
  .tipText {
    color: #cecece;
    text-align: left;
  }
  .attachConten {
    display: flex;
    flex-flow: wrap nowrap;
    .redPoint {
      color: red;
    }
    .attachTitle {
      width: 120px;
    }
    .tebleDiv {
      width: 100%;
    }
  }
  .orderTitle {
    height: 60px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 600px;
      height: 40px;
      line-height: 40px;
    }
    .remindColor {
      /deep/.el-input__inner {
        border: 1px solid red !important;
      }
    }
  }
  .noData {
    color: #adadad;
  }
  .btnDiv {
    display: inline-block;
    width: 100px;
  }
  .classficationTable /deep/.el-table__row :hover {
    cursor: pointer;
  }
  .testTable {
    height: 400px;
    margin-top: 15px;
  }
}
</style>